const AppError = require('../utils/appError')
const Category = require('../models/category')
const Article = require('../models/article')
const catchAsync = require('../utils/catchAsync')

/**
 * 创建分类
 * 需要--拦截器中间(提前获取到user和token信息)，权限验证
 */
exports.addCategory = catchAsync(async (req, res, next) => {
  const category = new Category(req.body)

  const savedCategory = await category.save()

  res.status(201).json({
    status: 'success',
    message: '分类创建成功',
    data: savedCategory,
  })
})

/**
 * 获取分类列表（分页）
 */
exports.pageCategory = catchAsync(async (req, res, next) => {
  const currentPage = +req.query.currentPage || 1
  const pageSize = +req.query.pageSize || 10
  const skip = (currentPage - 1) * pageSize

  const [list, total] = await Promise.all([
    Category.find().sort({ createdAt: -1 }).skip(skip).limit(pageSize),
    Category.countDocuments(),
  ])

  res.status(200).json({
    status: 'success',
    data: {
      list,
      total,
      pageSize,
      currentPage,
      totalPages: Math.ceil(total / pageSize),
    },
  })
})

/**
 * 根据 ID 获取单个分类
 */
exports.getCategory = catchAsync(async (req, res, next) => {
  const category = await Category.findById(req.params.id)
  if (!category) {
    return next(new AppError('分类不存在', 404))
  }

  res.status(200).json({
    status: 'success',
    data: category,
  })
})

/**
 * 更新分类
 * 需要--拦截器中间(提前获取到user和token信息)，权限验证
 */
exports.updateCategory = catchAsync(async (req, res, next) => {
  const category = await Category.findById(req.params.id)
  if (!category) {
    return next(new AppError('分类不存在', 404))
  }

  Object.assign(category, req.body)
  const updatedCategory = await category.save()

  res.status(200).json({
    status: 'success',
    message: '分类更新成功',
    data: updatedCategory,
  })
})

/**
 * 删除分类
 * 需要--拦截器中间(提前获取到user和token信息)，权限验证
 */
exports.deleteCategory = catchAsync(async (req, res, next) => {
  const category = await Category.findById(req.params.id)
  if (!category) {
    return next(new AppError('分类不存在', 404))
  }

  const articleCount = await Article.countDocuments({ category: category._id })
  if (articleCount > 0) {
    return next(new AppError('该分类下还有文章，无法删除', 400))
  }

  await Category.findByIdAndDelete(req.params.id)

  res.status(200).json({
    status: 'success',
    message: '分类删除成功',
    data: null,
  })
})

/**
 * 获取所有分类（不分页，用于下拉选择等）
 */
exports.getAllCategories = catchAsync(async (req, res, next) => {
  const categories = await Category.find().sort({ name: 1 })

  res.status(200).json({
    status: 'success',
    data: categories,
  })
})
